import { useSnippetsStore } from '@renderer/stores'

export function useTranslate () {
  const setSnippets = useSnippetsStore(state => state.setSnippets)

  async function translate (
    text: string,
    source?: string,
    target?: string,
  ) {
    if (!text) {
      setSnippets([])
      return
    }

    try {
      const res = await window.api.translate(text, source, target)
      setSnippets(
        res.web_trans['web-translation'].reduce<ISnippet[]>((acc, item, index) => {
          item.trans.forEach((i, j) => {
            acc.push({
              id: `${index}-${j}`,
              title: item.key,
              content: i.value,
              category_id: -1,
              created_at: '',
            })
          })

          return acc
        }, []),
      )
    } catch (e) {
      console.error(e)
    }
  }

  return {
    translate,
  }
}
